package com.example.wordroom

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private lateinit var wordDao: WordDao

    private lateinit var btnInsert: Button
    private lateinit var btnSelectAll: Button
    private lateinit var layoutWordContainer: LinearLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        wordDao = WordDataBase.getInstance(applicationContext).wordDao()
        initWidget()
    }

    private fun initWidget() {
        layoutWordContainer = findViewById(R.id.word_container)
        btnInsert = findViewById(R.id.btn_insert)
        btnSelectAll = findViewById(R.id.btn_select_all)
        btnSelectAll.setOnClickListener{
            // 清空LinearLayout
            layoutWordContainer.removeAllViews()
            // 查询数据库
            lifecycleScope.launch {
                val wordArray = wordDao.loadAllWords()
                // 构建单词列表视图
                for (word in wordArray) {
                    val text = TextView(applicationContext)
                    text.text = word.name
                    layoutWordContainer.addView(text)
                }
            }
        }

        btnInsert.setOnClickListener{
            // 往数据库中添加数据
            lifecycleScope.launch {
                val word = Word("hello","你好","hello,Liming")
                wordDao.insertWords(word)
            }
        }
    }
}